<?php
namespace Weixin\Controller;
use Think\Controller;
class IndexController extends TokenController {

    public function index(){
		//$this->valid();
		//$aa = str_replace("qrscene_","",'qrscene_46445');
		$this->responseMsg();
    }

	//验证令牌
	public function valid(){
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

	//生成微信菜单
	public function memu(){
		header("Content-type: text/html; charset=utf-8");
		$access_token = access_token();
		if($access_token){
			if($this->create_memu($access_token)){
				echo '菜单创建成功';
			}else{
				echo '失败';
			}
		}
	}
	
	//接收微信消息
	public function responseMsg(){
		//$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		$postStr = file_get_contents("php://input");
		if (!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);            	
			$fromUsername = $postObj->FromUserName;   //opneid
			$toUsername   = $postObj->ToUserName;     //获取原始微信号
			$keyword      = trim($postObj->Content);  //获取关键词
			$type         = trim($postObj->Event);    //获取事件类型
			$EventKey     = $postObj->EventKey;       //拉取key
			$time         = time();                   //时间戳
			$openid       = $fromUsername;            //openid
			$RX_TYPE      = trim($postObj->MsgType);  //消息类型
			$Ticket       = trim($postObj->Ticket);   //生成二维码场景 ticket (https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET)
			
			$msgType = "text";
			$textTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<Content><![CDATA[%s]]></Content>
						<FuncFlag>0</FuncFlag>
						</xml>"; 
			/*关注
			if($type == "subscribe"){
				//未关注 带参数二维码
				if(!empty($EventKey)){
					$scene_id = str_replace("qrscene_","",$EventKey);
					$datatext = $this->scan_subscribe($scene_id,$fromUsername);
				}else{
					$datatext = '关注我了'.$keyword.'-key='.$EventKey.'-'.$Ticket;
				}
				$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,$msgType,$datatext);
				echo $resultStr;
			}*/
			
			/*已关注 扫带参数二维码
			if($type == "SCAN"){
				$wxscan    = $this->wxscan($postObj);
				$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,$msgType,'扫我关注='.$keyword.'-key='.$EventKey.'-'.$fromUsername);
				echo $resultStr;
			}*/

			//消息类型分离
			switch ($RX_TYPE)
			{
				case "event":
					$result = $this->receiveEvent($postObj);
					break;
				case "text":
					$result = $this->receiveText($postObj);
					break;
				case "image":
					$result = $this->receiveImage($postObj);
					break;
				case "location":
					$result = $this->receiveLocation($postObj);
					break;
				case "voice":
					$result = $this->receiveVoice($postObj);
					break;
				case "video":
					$result = $this->receiveVideo($postObj);
					break;
				case "link":
					$result = $this->receiveLink($postObj);
					break;
				default:
					$result = "unknown msg type: ".$RX_TYPE;
					break;
			}
			//$this->logger("T \r\n".$result);
			echo $result;
        }
	}

	/*取消关注
	if($type == "unsubscribe"){
		$this->unsubscribe($fromUsername);
	}*/

	//接收事件消息
    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
            case "subscribe": 
                //$content = "欢迎关注 ".$object->EventKey.'-'.$object->Ticket;
				if(!empty($object->EventKey)){
					//扫码关注  扫参数二维码
					$scene_id = str_replace("qrscene_","",$object->EventKey);
					$content = $this->scan_subscribe($scene_id,$object->FromUserName);
				}else{
					$content = $this->subscribe($object->FromUserName);//传统关注
				}
                //$content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
                break;
            case "unsubscribe":
                $content = "取消关注";
				return $this->unsubscribe($object->FromUserName);
                break;
            case "CLICK":
                switch ($object->EventKey)
                {
                    case "COMPANY":
                        $content = array();
                        $content[] = array("Title"=>"坤亚科技", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
                        break;
                    default:
                        $content = "点击菜单：".$object->EventKey;
                        break;
                }
                break;
            case "VIEW":
                $content = "跳转链接 ".$object->EventKey;
                break;
            case "SCAN":
				$content = $this->wxscan($object);
                //$content = "扫描场景 ".$object->EventKey;
				//已关注 扫带参数二维码
                break;
            case "LOCATION":
                $content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
                break;
            case "scancode_waitmsg":
                if ($object->ScanCodeInfo->ScanType == "qrcode"){
                    //$content = "扫码二维码提示 结果：<a href='http://www.qq.com'>".$object->ScanCodeInfo->ScanResult."</a>";
                    $urll="http://www.baidu.com/s?wd=".$object->ScanCodeInfo->ScanResult;
                    $content[] = array("Title"=>"扫码二维码提示 结果", "Description"=>$object->ScanCodeInfo->ScanResult, "PicUrl"=>"http://www.qgzyrc.cn/seentao/images/logo.png", "Url" =>$urll);
                }else if ($object->ScanCodeInfo->ScanType == "barcode"){
                    $codeinfo = explode(",",strval($object->ScanCodeInfo->ScanResult));
                    $codeValue = $codeinfo[1];
                    $content = "扫码带提示：类型 条形码 结果：".$codeValue;
                }else{
                    $content = "扫码带提示：类型 ".$object->ScanCodeInfo->ScanType." 结果：".$object->ScanCodeInfo->ScanResult;
                }
                break;
            case "scancode_push":
                $content = "扫码推事件";
                break;
            case "pic_sysphoto":
                $content = "系统拍照";
                break;
            case "pic_weixin":
                $content = "相册发图：数量 ".$object->SendPicsInfo->Count;
                break;
            case "pic_photo_or_album":
                $content = "拍照或者相册：数量 ".$object->SendPicsInfo->Count;
                break;
            case "location_select":
                $content = "发送位置：标签 ".$object->SendLocationInfo->Label;
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }

        if(is_array($content)){
            if (isset($content[0]['PicUrl'])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

	//接收文本消息
    private function receiveText($object)
    {
        $keyword = trim($object->Content);

        //自动回复模式
        if (strstr($keyword, "文本")){
            $content = "这是个文本消息";
        }else if (strstr($keyword, "表情")){
            $content = "中国：".$this->bytes_to_emoji(0x1F1E8).$this->bytes_to_emoji(0x1F1F3)."\n仙人掌：".$this->bytes_to_emoji(0x1F335);
        /*}else if (strstr($keyword, "单图文")){
            $content = array();
            $content[] = array("Title"=>"单图文标题",  "Description"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"https://www.baidu.com");
        }else if (strstr($keyword, "图文") || strstr($keyword, "多图文")){
            $content = array();
            $content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"https://www.baidu.com");
            $content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"https://www.baidu.com");
            $content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"https://www.baidu.com");
        }else if (strstr($keyword, "音乐")){
            $content = array();
            $content = array("Title"=>"最炫民族风", "Description"=>"歌手：凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");*/ 
        }else if(strstr($keyword, "1818")){
			$content = "我的 <a href='http://".$_SERVER['HTTP_HOST'].U('/Home/User/myqrcode')."'>推广码</a>";
		}else if(strstr($keyword, "退出")){
            $content = "点击 <a href='http://".$_SERVER['HTTP_HOST']."/Home/Login/user_out.html'>退出登陆</a>\n\n技术支持 坤亚科技\n".date("Y-m-d H:i:s");
        }else if($keyword == '88'){
            $content = "点击 <a href='http://".$_SERVER['HTTP_HOST']."/Home/Login/user_out.html'>退出登陆</a>\n\n技术支持 坤亚科技\n".date("Y-m-d H:i:s");
        }else{
            $content = "中国：".$this->bytes_to_emoji(0x1F1E8).$this->bytes_to_emoji(0x1F1F3)."\n技术支持 坤亚科技\n\n".date("Y-m-d H:i:s");
            //$content = $this->wx_msg()."\n技术支持 坤亚科技\n\n".date("Y-m-d H:i:s");
        }

        if(is_array($content)){
            if (isset($content[0])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

	//回复文本消息
    private function transmitText($object, $content)
    {
        if (!isset($content) || empty($content)){
            return "";
        }
        $xmlTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[text]]></MsgType>
					<Content><![CDATA[%s]]></Content>
				</xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);

        return $result;
    }
	
	 //字节转Emoji表情
    function bytes_to_emoji($cp)
    {
        if ($cp > 0x10000){       # 4 bytes
            return chr(0xF0 | (($cp & 0x1C0000) >> 18)).chr(0x80 | (($cp & 0x3F000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x800){   # 3 bytes
            return chr(0xE0 | (($cp & 0xF000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x80){    # 2 bytes
            return chr(0xC0 | (($cp & 0x7C0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else{                    # 1 byte
            return chr($cp);
        }
    }

	//点击菜单
    public function ClickMenu($EventKey,$openid){
        
        /*
        if($EventKey=="V1001_SAO2"){
            $msgType = "news";
            $textTpl="<xml><ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[event]]></MsgType>
                    <Event><![CDATA[scancode_waitmsg]]></Event>
                    <EventKey><![CDATA[6]]></EventKey>
                    <ScanCodeInfo><ScanType><![CDATA[qrcode]]></ScanType>
                    <ScanResult><![CDATA[2]]></ScanResult>
                    </ScanCodeInfo>
                    </xml>";
            $contentStr = "验证会员！".WxConf::APPID;
            //$contentStr = "扫码带提示：类型 ".$object->ScanCodeInfo->ScanType." 结果：".$object->ScanCodeInfo->ScanResult;
            $conpe=array(
            	"msgType"=>$msgType,
                "contentStr"=>$contentStr,
                "textTpl"=>$textTpl,
            );
            return $conpe;
        	
        }*/
       
	   //我的业务
       if($EventKey=="V1001_YEWU"){
            $msgType = "news";
            $textTpl="<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[news]]></MsgType>
							<ArticleCount>1</ArticleCount>
							<Articles>
							<item>
							<Title><![CDATA[$openid 我的业务]]></Title> 
							<Description><![CDATA[我的业务]]></Description>
							<PicUrl><![CDATA[http://img.1985t.com/uploads/attaches/2013/04/10846-C4Aam4.jpg]]></PicUrl>
							<Url><![CDATA[http://www.xxx123.com?openid=$openid]]></Url>
							</item>
							</Articles>
						</xml> ";
            $contentStr = "我的业务！";
            $conpe=array(
            	"msgType"=>$msgType,
                "contentStr"=>$contentStr,
                "textTpl"=>$textTpl,
            );
            return $conpe;
        	
        }

		if($EventKey=="V1001_VIP"){
            $msgType = "text";
            $contentStr = "验证会员！";
            $conpe=array(
            	"msgType"=>$msgType,
                "contentStr"=>$contentStr,
            );
            return $conpe;
        }

        if($EventKey=="V1001_ZICHAN"){
            $msgType = "news";
            $textTpl  = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[news]]></MsgType>
							<ArticleCount>1</ArticleCount>
							<Articles>
							<item>
							<Title><![CDATA[我的资产]]></Title> 
							<Description><![CDATA[我的资产]]></Description>
							<PicUrl><![CDATA[http://img.1985t.com/uploads/attaches/2013/04/10846-C4Aam4.jpg]]></PicUrl>
							<Url><![CDATA[http://www.xxx123.com?openid=$openid]]></Url>
							</item>
							</Articles>
						</xml> ";
            
            $contentStr = "我的资产！";
            $conpe      = array(
            	"msgType"   => $msgType,
                "contentStr"=> $contentStr,
                "textTpl"   => $textTpl,
            );
            return $conpe;
        	
        }

        if($EventKey=="V1003_HEZUO"){
            $str  = "商务合作！".$openid;
            $data = array(
            	"msgType"    => "text",
                "contentStr" => $str,
            );
            return $data;
        }
    	
    }

	private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
		$token = C('wx_token');
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}

	 //日志记录
    private function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 1000000;
            $log_filename = "/log/log.log";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }

	/**
	* 扫码关注 (带参数的二维码)
	* @scene_id   扫码场景参数 UID
	* @openid
	*/
	public function scan_subscribe($scene_id,$openid){
		import('Class.File',APP_PATH);
		$log = new \File(); //实例化文件类

		$wxinfo = wx_info($openid,access_token());
		$log->write($wxinfo,'logs/weixin');
		if($wxinfo == false) return false;
		
		$insert = array(
			'openid'    => $wxinfo['openid'],
			'unionid'   => @$wxinfo['unionid'],
			'nickname'  => urlencode($wxinfo['nickname']),//微信昵称
			'headimgurl'=> $wxinfo['headimgurl'],         //微信头像
			'created_at'=> date('Y-m-d H:i:s'),           //初次关注时间
			'scan_id'   => $scene_id,                     //推广人ID  二维码场景
			'wx_status' => '1',
		);
		$where = array('openid'=>strval($openid));
		$user = M('user')->field(['id'])->where($where)->find();

		if($user){
			//欢迎再次回来
			unset($insert['scan_id']);
			$data = $this->subscribe($openid);
			$this->scancount(array('openid'=>$where['openid'],'scan_id'=>$scene_id,'scan_type'=>3));
		}else{
			$vip = C('IS_TRIAL_VIP');
			if($vip){
				$insert['vip_type']    = '1';
				$insert['chance']      = '300';
				$insert['vip_end_time']= strtotime("+5 days");
			}
			M()->startTrans();
			try{
				M('qrcode')->where(array('uid'=>$scene_id))->setInc('scan_count');
				M('user')->where(array('id'=>$scene_id))->setInc('count_tg');
				$uid = M('user')->add($insert);
				M()->commit();
			}catch (\Exception $e) {
				M()->rollback();
			}
			//$data = "欢迎关注我，{$wxinfo['nickname']} \n\r您的ID:$uid ";
			$data = "{$wxinfo['nickname']} 欢迎关注！\n\n";
			$data .= $this->wx_msg();
			$this->scancount(array('openid'=>$where['openid'],'scan_id'=>$scene_id,'scan_type'=>1));
		}
		return $data;
		
		/*$msgType = "news";
		$textTpl="<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<ArticleCount>1</ArticleCount>
						<Articles>
						<item>
						<Title><![CDATA[%s]]></Title> 
						<Description><![CDATA[%s]]></Description>
						<PicUrl><![CDATA[http://img.1985t.com/uploads/attaches/2013/04/10846-C4Aam4.jpg]]></PicUrl>
						<Url><![CDATA[http://www.xxx123.com?openid=$openid]]></Url>
						</item>
						</Articles>
					</xml> ";
		$contentStr = "我的业务！";
		$conpe=array(
			"msgType"=>$msgType,
			"contentStr"=>$contentStr,
			"textTpl"=>$textTpl,
		);
	
		$resultStr = sprintf($textTpl, $openid, $openid, time(), $msgType, $openid,$openid);
		//$resultStr = sprintf($textTpl, $postObj->fromUsername, $postObj->toUsername, time(), $msgType, $postObj->contentStr,$postObj->fromUsername);
        return $resultStr;*/
		//return true;
		
	}

	/**
	* 普通关注
	* @openid
	*/
	public function subscribe($openid){
		$wxinfo = wx_info($openid,access_token());
		if($wxinfo == false) return false;
		
		$insert = array(
			'openid'    => $wxinfo['openid'],
			'unionid'   => @$wxinfo['unionid'],
			'nickname'  => urlencode($wxinfo['nickname']),//微信昵称
			'headimgurl'=> $wxinfo['headimgurl'],         //微信头像
			'created_at'=> date('Y-m-d H:i:s'),                        //初次关注时间
			'wx_status' => '1',
		);
		$db   = M('user');
		$user = $db->field(['id','scan_id'])->where(['openid'=>strval($openid)])->find();
		if($user){
			$insert['id']             = $user['id'];
			$insert['subscribe_time'] = $wxinfo['subscribe_time'];
			unset($insert['created_at']);
			$db->save($insert);
			
			$scan_id = $user['scan_id'];
			$uid     = $user['id'];
			$text    = "{$wxinfo['nickname']} 欢迎回家！\n\n";
			$text    .= $this->wx_msg();
		}else{
			$vip = C('IS_TRIAL_VIP');
			if($vip){
				$insert['vip_type']    = '1';
				$insert['chance']      = '300';
				$insert['vip_end_time']= strtotime("+5 days");
			}
			$uid  = $db->add($insert);
			$text = "{$wxinfo['nickname']} 欢迎关注！\n\n";
			$text .= $this->wx_msg();
		}
		//$data = $text."\n\r您的ID:$uid";
		return $text;
	}

	//取消关注
	public function unsubscribe($openid){
		$data = array('wx_endtime'=>time(),'wx_status'=>'0');
		M('user')->where(['openid'=>strval($openid)])->save($data);
	}

	/**
	*	微信扫码
	*	$fromUsername = $postObj->FromUserName;   //opneid
		$toUsername   = $postObj->ToUserName;     //获取原始微信号
		$keyword      = trim($postObj->Content);  //获取关键词
		$type         = trim($postObj->Event);    //获取事件类型
		$EventKey     = $postObj->EventKey;       //拉取key
		$time         = time();                   //时间戳
		$openid       = $fromUsername;            //openid
		$RX_TYPE      = trim($postObj->MsgType);  //消息类型
		$Ticket       = trim($postObj->Ticket);   //生成二维码场景
	*/
	public function wxscan($object){
		$obj  = (array)$object;
		$type = 2;//扫码类型 1关注扫码，2重复扫码， 3重新关注扫码，4自己扫自己
		$uid  = $obj['EventKey'];
		$user = M('user')->field(array('nickname','headimgurl'))->where(['id'=>$uid])->find();
		if($user){
			$userid = M('user')->where(['openid'=>$obj['FromUserName']])->getField('id');
			if($userid == $uid){
				$type = 4;
			}
		}
		$data = array(
			'openid'   => $obj['FromUserName'],
			'scan_id'  => $uid,
			'scan_type'=> $type,
		);
		$this->scancount($data);
		
		$str = "扫码场景：{$uid}\n\r";
		if($user){
			$user['nickname'] = urldecode($user['nickname']);
		}
		$str .= "扫码对象：{$user['nickname']} - [<a href='".$user['headimgurl']."'> 头像 </a>]";
		return $str;
	}

	//扫码记录
	public function scancount($data){
		$data['scan_time'] = time();
		M('scancount')->add($data);
		M('user')->where(['id'=>$data['scan_id']])->setInc('scan_number');
		//logw(M('user')->_sql());
	}

	//创建自定义菜单
	public function create_memu($access_token){
		/*$db=M('weixin_conf');
		$memu=$db->where('id=1 and type=1')->find();
		$data=unserialize($memu['content']);
		serialize
		//$data=json_encode($data,true);*/
		//$url  = 'http://'.$_SERVER['HTTP_HOST'];
		$url  = 'http://'.$_SERVER['HTTP_HOST'];
		$data = array(
			'button'=>array(
				array('type'=>'view','name'=>urlencode('发现'),'url'=>$url.U('/Home/Index/index')),
				array('type'=>'view','name'=>urlencode('发布'),'url'=>$url.U('/Home/Goods/goodsadd')),
				array(
					'name'=>urlencode('个人中心'),
					'sub_button'=>array(
						array('type'=>'view','name'=>urlencode('发布管理'),'url'=>$url.U('/Home/Goods/mygood')),
						array('type'=>'view','name'=>urlencode('个人信息'),'url'=>$url.U('/Home/User/usercode')),
						//array('type'=>'view','name'=>urlencode('我的推广码'),'url'=>$url.U('/Home/User/myqrcode')),
						array('type'=>'view','name'=>urlencode('会员充值'),'url'=>$url.U('/Home/User/viplist','','')),
					),
				),
			),	
		);
		$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
		$data= urldecode(json_encode($data,JSON_UNESCAPED_UNICODE));

		$post=https_post($url,$data,1);
		if($post['errcode'] == '0'){
			return true;
		}else{
			return false;
		}	
	}

	//回复图文消息
    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return "";
        }
        $itemTpl = "<item>
					<Title><![CDATA[%s]]></Title>
					<Description><![CDATA[%s]]></Description>
					<PicUrl><![CDATA[%s]]></PicUrl>
					<Url><![CDATA[%s]]></Url>
				</item>";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[news]]></MsgType>
					<ArticleCount>%s</ArticleCount>
					<Articles>$item_str</Articles>
				</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

    //回复音乐消息
    private function transmitMusic($object, $musicArray)
    {
        if(!is_array($musicArray)){
            return "";
        }
        $itemTpl = "<Music>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <MusicUrl><![CDATA[%s]]></MusicUrl>
        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
    </Music>";

        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $xmlTpl = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[music]]></MsgType>
				$item_str
			</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复图片消息
    private function transmitImage($object, $imageArray)
    {
        $itemTpl = "<Image>
					<MediaId><![CDATA[%s]]></MediaId>
				</Image>";

        $item_str = sprintf($itemTpl, $imageArray['MediaId']);

        $xmlTpl = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[image]]></MsgType>
				$item_str
			</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复语音消息
    private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "<Voice>
					<MediaId><![CDATA[%s]]></MediaId>
				</Voice>";

        $item_str = sprintf($itemTpl, $voiceArray['MediaId']);
        $xmlTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[voice]]></MsgType>
					$item_str
				</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复视频消息
    private function transmitVideo($object, $videoArray)
    {
        $itemTpl = "<Video>
        <MediaId><![CDATA[%s]]></MediaId>
        <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
    </Video>";

        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

        $xmlTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[video]]></MsgType>
					$item_str
				</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

	//更新带参数的二维码
	public function uploadcode(){
		$this->error('请联系管理员');die;
		if(IS_POST){
			$uid    = I('uid',0,intval);
			if(empty($uid)){
				$this->error('参数错误');
			}
			$user   =M('user')->field(['id','headimgurl'])->where(['id'=>$uid])->find();
			//p($user);
			if(!$user){
				$this->error('参数错误');
			}
			$images = loadwximages($uid);
			if($images){
				$images['endtime'] = date('Y-m-d H:i:s',(time()+ $images['expire']));
				//p($images);
				//保存到本地
				if($user['headimgurl']){
					$downwx  = downweixin_curl($images['img']);
					$names   = $uid.'_'.uniqid().'.jpg';
					$headico = downweixin_curl($user['headimgurl'],$names);

					if($downwx && $headico){
						//增加水印头像
						$img = qrcode_water($downwx,$headico);
						//p($img,1);
						if($img){
							M('qrcode')->where(['uid'=>$uid])->save(['img'=>$img]);
							$images['img'] = $img;
						}
					}
				}

				$this->ajaxReturn(array('info'=>'更新成功','data'=>$images,'status'=>'1'));
			}
		}
		$this->error('更新失败');
	}

	//关注消息
	public function wx_msg(){
		$str  = "财源滚滚和苟延残喘间\n";
		$str .= "仅相差一个道理——\n\n";
		$str .= "在这个新兴的年代，中间商如果不会利用互联网进行自我推广，就是死路一条。\n";
		$str .= "借道是为中间商量身定制的最适合中间商的掌上自助推广平台，是中间商与中间商之间的“搭桥者”。通过全国巨量的中间商商品，让你找到最适合自己的中间商。通过最直接、最简单、最高效的推广方式提高你的曝光率，让更多中间商找到你。\n\n";
		$str .= "没有不赚钱的中间商，\n";
		$str .= "只有不会赚钱的中间商。\n";
		$str .= "点击链接了解借道↓\n\n";
		$str .= "<a href='http://h.eqxiu.com/s/XdK263ui'>（新手教程链接）</a>\n\n";
		$str .= "你已经浪费了太多机会，\n";
		$str .= "现在除了借道，\n";
		$str .= "你没有别的选择。";

		return $str;

	}

	//End
}

